package com.jy.api.service.impl;

import com.jy.api.dao.*;
import com.jy.api.domain.*;
import com.jy.api.domain.CallService;
import com.jy.api.service.*;
import com.jy.api.signUpReq.MarsCallReq.*;
import com.jy.api.util.MyDateUtils;
import com.jy.api.util.Result;
import com.jy.api.util.UuidUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import sun.rmi.runtime.Log;

import java.text.NumberFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by xiaohua on 2018/11/12.
 */
@Service
@Slf4j
public class RewardServiceImpl implements RewardService {

    @Autowired
    private ProductDao productDao;
    @Autowired
    private MemberDao memberDao;
    @Autowired
    private EmployeeDao employeeDao;
    @Autowired
    private RewardDao rewardDao;
    @Autowired
    private AppraiseDao appraiseDao;


    @Override
    @Transactional
    public Map<String, Object> createRewardOrder(RewardOrderReq req) {
        Result result = null;
        Map<String, Object> map = new HashMap<>();
        Object data = null;
        map.put("data", data);
        Employee employee = employeeDao.findOne(req.getEmpId());
        if (employee == null) {
            result = new Result(400, "该服务员不存在，请联系网吧人员");
            map.put("result", result);
            return map;
        }
        Product product = productDao.findOne(req.getProductId());
        if (product == null) {
            result = new Result(400, "该商品不存在，请联系网吧人员");
            map.put("result", result);
            return map;
        }
        if (req.getTotal() <= 0) {
            map.put("result", new Result(400, "订单金额必须大于0"));
            return map;
        }
        Reward reward = new Reward(req, employee.getName(), product.getName(), product.getImageURL());
        Reward r = rewardDao.save(reward);
        result = new Result(200, "商品添加成功");
        map.put("data", r);
        map.put("result", result);
        return map;
    }

    @Override
    @Transactional
    public Reward updateReward(RewardUpdateReq req) {
        Reward reward = rewardDao.findOne(req.getId());
        if (StringUtils.equals(reward.getProductId(), req.getProductId())) {
            reward.setTotal(req.getAmount());
            reward.setCount(req.getCount());
        } else {
            Product product = productDao.findOne(req.getProductId());
            reward.setCount(req.getCount());
            reward.setTotal(req.getAmount());
            reward.setProductId(product.getId());
            reward.setProductName(product.getName());
            reward.setProductImageurl(product.getImageURL());
        }
        return rewardDao.save(reward);
    }

    @Override
    public Page<Reward> getRewardItem(String storeId, Pageable pageable) {
        return rewardDao.findByStoreIdAndStatusAndEnabledOrderByPaymentTimeDesc(storeId, OrderStatus.FINISHED, true, pageable);
    }

    @Override
    public Map<String, Object> getRewardRanking(String storeId, String empId) {
        List<Object[]> objects = rewardDao.findSumRewardAndOrderByAmountAsc(storeId,empId);
        List<Object[]> list = rewardDao.findTotalOrderByAmountAsc(storeId,empId);
        Date begin = MyDateUtils.getMinMonthDate();
        Date end = MyDateUtils.getMaxMonthDate();
        List<Object[]> appraise = appraiseDao.findSumRewardAndOrderByAmountAsc(storeId,empId,begin,end);
        Map<String,Object> map = new HashMap<>();
        List<RewardRankingRes> res = new ArrayList<>();
        for (Object[] ob : objects) {
            RewardRankingRes data = new RewardRankingRes();
            data.setAmount(Double.valueOf(ob[2].toString()));
            data.setCount(Integer.valueOf(ob[1].toString()));
            data.setMemberName(ob[0].toString());
            res.add(data);
        }
        for (Object[] obj : list) {
            map.put("totalCount",obj[0]);
            map.put("totalAmount",obj[1]);
        }
        NumberFormat nf = NumberFormat.getNumberInstance();
        nf.setMaximumFractionDigits(2);
        nf.setGroupingUsed(false);
        double totalAppraise = 0;
        double people= 0;
        for (Object[] app : appraise) {
            people =Double.valueOf(app[0].toString());
            totalAppraise =Double.valueOf(app[1].toString());
        }
        map.put("totalService",people);
        if (people==0){
            map.put("totalAppraise",0);
        }else{
            map.put("totalAppraise",totalAppraise / people);
        }

        map.put("list",res);
        return map;
    }

    @Override
    public EmpRewardRes getEmpRewards(String empId, String from, String source, String type, String storeId, Integer year, Integer month, String judge) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        simpleDateFormat.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai"));
        EmpRewardRes rewardRes = new EmpRewardRes();
        Date start = null;
        Date end = null;
        Date dataSourceTime = null;
        double amount = 0.0;
        int count = 0;
        List<Reward> rewards = null;
        if (StringUtils.equals(source, "DAY")) {
            try {
                dataSourceTime = simpleDateFormat.parse(from);
                start = MyDateUtils.getEarliest(dataSourceTime);
                end = MyDateUtils.getLastest(dataSourceTime);
            } catch (ParseException e) {
                log.info("时间转换异常");
                e.printStackTrace();
            }
        } else {
            String s = year + "-" + month;
            start = MyDateUtils.getMinMonthDate(s);
            end = MyDateUtils.getMaxMonthDate(s);
        }
        if (StringUtils.equals("EMP", type)) {
            rewards = rewardDao.findByEmpIdAndPaymentTimeBetweenAndStatusAndEnabled(empId, start, end, OrderStatus.FINISHED, true);
        } else {
            if (StringUtils.equals("ALL", judge)) {
                rewards = rewardDao.findByStoreIdAndPaymentTimeBetweenAndStatusAndEnabled(storeId, start, end, OrderStatus.FINISHED, true);
            } else {
                rewards = rewardDao.findByEmpIdAndPaymentTimeBetweenAndStatusAndEnabled(judge, start, end, OrderStatus.FINISHED, true);
            }
        }
        List<EmpRewardRes.Rew> rews = new ArrayList<>();
        for (Reward re : rewards) {
            EmpRewardRes.Rew rew = new EmpRewardRes.Rew();
            rew.setAddTime(re.getCreateTime());
            rew.setAmount(re.getTotal());
            rew.setName(re.getMemberName());
            rew.setQty(re.getCount());
            rew.setEmpName(re.getEmpName());
            rews.add(rew);
            amount += re.getTotal();
            count += rew.getQty();
        }
        rewardRes.setCount(count);
        rewardRes.setRews(rews);
        rewardRes.setTotal(amount);
        return rewardRes;
    }

    @Override
    public Map<String, Object> getMemberInfo(String id) {
        Reward reward = rewardDao.findOne(id);
        Map<String, Object> map = new HashMap<>();
        if (null == reward.getMemberId()) {
            map.put("state", 0);
            map.put("data", null);
            return map;
        }
        Member member = memberDao.findOne(reward.getMemberId());
        if (member != null) {
            map.put("state", 1);
            map.put("data", member.getId());
        } else {
            map.put("state", 0);
            map.put("data", null);
        }
        return map;


    }

    @Override
    @Transactional
    public Map<String, Object> updateMemberByMemberId(MemberRewardReq req) {
        Reward reward = rewardDao.findOne(req.getId());
        Member member = memberDao.findOne(req.getMemberId());
        Map<String, Object> map = new HashMap<>();
        if (member != null) {
            reward.setMemberId(req.getMemberId());
            reward.setMemberName(member.getName());
            Reward returnReward = rewardDao.save(reward);
            map.put("result", new Result(200, "会员添加成功"));
            map.put("data", returnReward);
            return map;
        } else {
            map.put("result", new Result(400, "该会员不存在"));
            return map;
        }
    }

    @Override
    public List<RewEmpRes> getEmp(String storeId) {
        List<Employee> employees = employeeDao.findListByStoreIdAndEnabled(storeId, true);
        List<RewEmpRes> list = new ArrayList<>();
        for (Employee c : employees) {
            RewEmpRes res = new RewEmpRes();
            res.setEmpId(c.getId());
            res.setEmpName(c.getName());
            list.add(res);
        }
        return list;
    }
}
